<template>
  <div>
    <el-dialog
      :title="isEdit ? '编辑备件' : '添加备件'"
      :visible.sync="dialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-form-item label="备件编号" prop="partNo">
          <el-input v-model="form.partNo" placeholder="请输入备件编号" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="备件名称" prop="partName">
          <el-input v-model="form.partName" placeholder="请输入备件名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specNo">
          <el-input v-model="form.specNo" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="备件类型" prop="partTypeCode">
          <el-select v-model="form.partTypeCode" placeholder="请选择备件类型" style="width: 100%">
            <el-option
              v-for="type in partTypeOptions"
              :key="type.code"
              :label="type.name"
              :value="type.code"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="备件仓库" prop="warehouseCode">
        <el-select v-model="form.warehouseCode" placeholder="请选择备件仓库" style="width: 100%" filterable>
          <el-option
            v-for="w in warehouseOptions"
            :key="w.warehouseCode || w.code || w.value"
            :label="w.warehouseName || w.name || w.label"
            :value="w.warehouseCode || w.code || w.value"
          />
        </el-select>
      </el-form-item>
        
        <!-- 关联资产 -->
        <el-form-item label="关联资产">
          <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
            <el-tag
              v-for="asset in selectedAssets"
              :key="asset.id"
              closable
              @close="removeAsset(asset.id)"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ asset.assetNo }} - {{ asset.assetName }}
            </el-tag>
            <el-button type="primary" size="small" @click="showAssetSelector = true">
              快速选择
            </el-button>
          </div>
        </el-form-item>
        
        <!-- 图片上传 -->
        <el-form-item label="备件图片">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :file-list="form.images"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :before-upload="beforeUpload"
            list-type="picture-card"
            :limit="5"
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB，最多5张
            </div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="是否启用" prop="enabled">
          <el-switch v-model="form.enabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 资产选择弹窗 -->
    <el-dialog
      title="快速选择资产"
      :visible.sync="showAssetSelector"
      width="800px"
      append-to-body
    >
      <asset-selector
        :selected-assets="selectedAssets"
        :multiple="true"
        :onlyAbnormal="false"
        @confirm="handleAssetSelect"
        @cancel="showAssetSelector = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import AssetSelector from '@/views/components/AssetSelector.vue'
import { getPart, addPart, updatePart } from '@/api/inventory/part'
import { getToken } from '@/utils/auth'

export default {
  name: 'PartForm',
  components: { AssetSelector },
  props: {
    mode: { type: String, default: 'create' },
    code: { type: String, default: '' },
    visible: { type: Boolean, default: false }
  },
  data() {
    return {
      dialogVisible: false,
      showAssetSelector: false,
      selectedAssets: [],
      warehouseOptions: [],
      partTypeOptions: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      form: {
        partNo: null,
        partName: null,
        specNo: null,
        partTypeCode: null,
        warehouseCode: null,
        enabled: 1,
        images: []
      },
      rules: {
        partNo: [{ required: true, message: '备件编号不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '备件名称不能为空', trigger: 'blur' }],
        specNo: [{ required: true, message: '规格型号不能为空', trigger: 'blur' }],
        partTypeCode: [{ required: true, message: '请选择备件类型', trigger: 'change' }],
        warehouseCode: [{ required: true, message: '请选择备件仓库', trigger: 'change' }]
      }
    }
  },
  computed: {
    isEdit() {
      return this.mode === 'edit'
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.initForm()
        this.loadWarehouses()
        this.loadPartTypes()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    loadWarehouses() {
      if (this.$warehouseLoaded) return
      import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouse || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
            this.warehouseOptions = res.rows || res.data || []
            this.$warehouseLoaded = true
          })
        }
      }).catch(() => {})
    },
    // 加载备件类型列表
    loadPartTypes() {
      if (this.$apiPartTypeLoaded) return
      import('@/api/dict/partType').then(mod => {
        const listFn = mod.listPartType || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999, enabled: 1 }).then(res => {
            this.partTypeOptions = res.rows || res.data || []
            this.$apiPartTypeLoaded = true
          })
        }
      }).catch(() => {})
    },
    // 初始化表单
    initForm() {
      if (this.isEdit && this.code) {
        // 编辑模式，获取数据
        getPart(this.code).then(response => {
          this.form = { ...response.data }
          this.selectedAssets = response.data.assets || []
        })
      } else {
        // 新增模式，重置表单
        this.form = {
          partNo: null,
          partName: null,
          specNo: null,
          partTypeCode: null,
          warehouseCode: null,
          enabled: 1,
          images: []
        }
        this.selectedAssets = []
      }
    },
    
    // 确认提交
    handleConfirm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        
        const formData = {
          ...this.form,
          assets: this.selectedAssets
        }
        
        const action = this.isEdit ? updatePart : addPart
        action(formData).then(() => {
          this.$message.success(this.isEdit ? '修改成功' : '添加成功')
          this.dialogVisible = false
          this.$emit('success')
        }).catch(() => {
          this.$message.error(this.isEdit ? '修改失败' : '添加失败')
        })
      })
    },
    
    // 取消操作
    handleCancel() {
      this.dialogVisible = false
    },
    
    // 移除关联资产
    removeAsset(assetId) {
      this.selectedAssets = this.selectedAssets.filter(asset => asset.id !== assetId)
    },
    
    // 处理资产选择确认
    handleAssetSelect(assets) {
      this.selectedAssets = assets
      this.showAssetSelector = false
    },
    
    // 上传前检查
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    
    // 上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('图片上传成功')
        this.form.images = fileList
      } else {
        this.$message.error('图片上传失败')
      }
    },
    
    // 移除图片
    handleUploadRemove(file, fileList) {
      this.form.images = fileList
    }
  }
}
</script>
